﻿/*
   @Description:agency员工管理js
   @Author:wk
   @Date:2014-08-10 
 */
var employeeIndex = {};

//搜索人员信息后将搜索到的总人数传到主页面显示
employeeIndex.findUsers = function () {
    var totalCount = $("#hiddTotalCount").val();
    $(".totalCount").text(totalCount);
    other.hideLoaderMask();
};

//动态添加部门和角色
employeeIndex.addDepartRole = function () {
    $(".addDepartRole").bind("click", function () {
        //添加的时候隐藏锁定状态
        $(".departAndRolehtml .lockFlag").hide();
        $("#spanTest").find(".departAndRole").append($(".departAndRolehtml").html());
        var i = 0;
        $("#spanTest").find(".departAndRole > div").each(function () {
            i++;
            if (i > 1) {
                var lastDepartName = $(this).find(".addEmployeeDeparthidd").unbind();
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").unbind();

                var lastDepartName = $(this).find(".addEmployeeDeparthidd").attr("id", "txtAddEmployeeDepart" + i);
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").attr("id", "txtAddEmployeeDepartKey" + i);
                //每次添加都会给一个新的ID
                EmployeePrompt.getDepartAndEmployeeByInput(lastDepartName.attr("id"), lastDepartKey.attr("id"), null, null, false, false, 1, null, "");
            }
        });
    })
}
//添加员工相关方法结束 end


//获取选中记录的KeyId
employeeIndex.GetEmployeeKeys = function () {
    var employeeKeyId = "";
    $("#treeTable .checkStaff:checked").each(function () {
        employeeKeyId += $(this).val() + ",";
    });
    return employeeKeyId;
}

//删除部门和角色文本框信息
employeeIndex.DelDepartAndRole = function (e) {
    var userKeyId = $(e).next().val();
    var depatKeyId = $(e).next().next().val();
    if ($("#spanEditemployee .departAndRole > div").length == 1) {
        $.OKDialogAgency('<center>无法删除该员工的唯一部门！</center>');
        return
    }
    if (userKeyId != undefined && depatKeyId != undefined) {  //如果不存在KeyId说明是新添加
        var reqData = {
            "userKeyId": userKeyId,
            "depatKeyId": depatKeyId
        };
        $.AjaxAgency("/system/check-userdepat-resource", reqData, function (data) {
            if (data == "True") {
                $(e).parent().remove();
            }
            else {
                $.OKDialogAgency('<center>' + data + '</center>');
            }
        });
    }
    else {
        $(e).parent().remove();
    }
}


//按钮状态切换
employeeIndex.ModifyBtnStatus = function (selector, addclass, removeclass) {
    //变化按钮状态
    selector.addClass(addclass);
    selector.removeClass(removeclass);
};

//转移员工使用的方法 start
//转移员工的tab标签切换方法
employeeIndex.transferStaffTab = function () {
    var editTabMenu = $("#spanTransferStaff .tab-nav li");
    var editTabCont = $("#spanTransferStaff .tab-bd .tab-panel");
    editTabMenu.each(function () {
        $(this).click(function () {
            var index = editTabMenu.index(this);
            $(this).addClass("current").siblings().removeClass("current");
            editTabCont.eq(index).css("display", "block").siblings().css("display", "none");
        });
    });
};
employeeIndex.initTransferStaffTab = function (titleID, contentID) {
    var option = {
        titleID: titleID,
        contentID: contentID,
        currentClassName: "current",
        titleFun: employeeIndex.getTitles,
        urlFun: employeeIndex.getTabUrl,
        dataFun: employeeIndex.getData,
        isIframe: true,
        contentFun: null
    };
    tabHelper(option);
}
employeeIndex.getTitles = function () {
    return ["全部房源", "全部客源", "全部钥匙", "全部实勘", "全部签约", "全部转介房", "全部业绩声明","委托备案"];
}
var userKeyId;
var depatKeyId = "";
employeeIndex.getTabUrl = function (tabname) {
    var urlNum = window.location.href.split('=')[1];
    if (tabname == "全部客源") {
        return "/system/all-inquiry?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部房源") {
        return "/system/all-property?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部钥匙") {
        return "/system/all-key?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部实勘") {
        return "/system/all-real?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部转介房") {
        return "/system/all-propertyMyTurn?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部签约") {
        return "/system/all-onlyTrust?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "全部业绩声明") {
        return "/system/all-performances?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    if (tabname == "委托备案") {
        return "/system/all-trustRecords?userId=" + userKeyId + "&depatId=" + depatKeyId;
    }
    //if (tabname == "广告") {
    //    return "/system/all-advertRecords?userId=" + userKeyId + "&depatId=" + depatKeyId;
    //}
};
employeeIndex.getData = function (tabname) {
    return [{ name: "key", value: tabname }];
}

//confirm点击确定执行的回调函数
employeeIndex.UpdateEmployeeStutas = function (employeeKeyId) {
    $('#userStatusModify i').attr('class', 'icon-statusModify');
    $(".statusModify").hide();
    var employeeStutas = $("#inquiryStatusKeyIdAll input[type=radio]:checked").val();
    var reqData = {
        "employeeStutas": employeeStutas,
        "employeeKeyId": employeeKeyId
    };
    $.AjaxAgency("/system/UpdateEmployeeStutas", reqData, function (data) {
        if (data == "OK") {
            $('#btnChangeCustomerStatu').removeAttr('disabled');
            $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                $(".userSubmit").submit();
            });
        }
        else {
            $.OKDialogAgency('<center>' + data + '</center>');
        }
    });
};

$(function () {

    //初始化绑定用户的智能提示（用于员工列表页员工搜索框）
    EmployeePrompt.getEmployeeByInput("txtfindEmployeeName", "txtfindEmployeeKey", false, 'private', null, true);
    //初始化部门绑定的智能提示（用于员工列表页员工搜索框）
    EmployeePrompt.getDepartAndEmployeeByInput("txtfindDepartName", "txtfindDepartKey", null, null, false, false, 1, null, "请选择部门");

    //动态的角色绑定数据
    employeeIndex.getRoles($(".EmployeeRole"));

    //绑定查询条件的角色下拉框
    employeeIndex.getRoles($(".roleSelect"));

    //转移员工  批量转移（暂未使用）
    $(".transfer-staff").click(function () {
        //弹层显示拼接的元素
        $.dialog({
            id: "dialogTransferStaff",
            lock: true,
            title: "转移员工",
            width: 800,
            content: '<span id="spanTransferStaff">' + $("#transferData").html() + '</span>',
        });
        //动态绑定Tab页切换
        employeeIndex.initTab();
        employeeIndex.transferStaffTab();
        //部门职能提示
        EmployeePrompt.getDepartAndEmployeeByInputExcCode("spanTransferStaff .userDepatRoleCheck input[type=checkbox]", "txtTransferDepartName", "txtTransferDepartKey", null, null, false, false, 1, null, "请选择部门");
    });


    //批量更改人员状态操作
    $('#userStatusModify').unbind('click');
    $('#userStatusModify').click(function () {
        var currentParentClass = $('#userStatusModify').attr("class");
        if (currentParentClass.lastIndexOf("btn-blue") > -1) {
            var currentClass = $('#userStatusModify i').attr("class");
            if (currentClass == 'icon-statusModify') {
                $('#userStatusModify i').attr('class', 'icon-statusModify-on');
                $(".statusModify").show();
            } else {
                $('#userStatusModify i').attr('class', 'icon-statusModify');
                $(".statusModify").hide();
            }
        }

        function tempFunc2() {
            $('#userStatusModify i').attr('class', 'icon-statusModify');
        }
        employeeIndex.showAndHide('#userStatusModify', 'inquiryStatusKeyIdAll', tempFunc2, 'iStatusModify');
        $('#btnChangeUserStatu').unbind('click');
        $('#btnChangeUserStatu').click(function () {
            var employeeKeyId = employeeIndex.GetEmployeeKeys();
            if (employeeKeyId == "") {
                $.OKDialogAgency('<center>请选择需要变更状态的人员记录！</center>');
                return false;
            }
            //状态变更的确认逻辑
            $.OKCancelDialogAgency("确认变更状态为" + $("#inquiryStatusKeyIdAll input[type=radio]:checked").next().text() + "？", "状态更改", true, function () {
                employeeIndex.UpdateEmployeeStutas(employeeKeyId);
            }, null);
        });
    });

    //批量删除员工(暂时未使用)
    $('.del-staff').unbind('click');
    $(".del-staff").bind("click", function () {
        //获取需要删除的员工Key
        var employeeKeyId = employeeIndex.GetEmployeeKeys();
        if (employeeKeyId == "") {
            $.OKDialogAgency('<center>请选择需要删除的人员记录！</center>');
        }
        else {
            if (confirm("确认删除该员工在Agency中的账号么？")) {
                var url = "/System/DeleteEmployeeStutas";
                var reqData = {
                    "employeeKeyId": employeeKeyId
                };
                $.AjaxAgency(url, reqData, function (data) {
                    if (data == "OK") {
                        $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                            window.location = "/system/employee";
                        });
                    }
                    else {
                        $.OKDialogAgency('<center>' + data + '</center>');
                    }
                });
            }
        }
    });

    //添加员工相关方法开始 start
    //新增员工
    $('#addEmployee').unbind('click');
    $("#addEmployee").bind("click", function () {
        //弹层显示拼接的元素
        $.dialog({
            id: "dialogProprietorEmployee",
            lock: true,
            title: "新增员工",
            content: '<div id="spanTest">' + $(".addStaff").html() + '</div>'
        });
        
        //身份证号验证
        agencyVerify.regexCheckIDCard(null, "#txtUID", '请正确录入身份证18位，护照8至10位', true, "blur", null);
        //判断用户类型
        $("#spanTest input[name=UserType]").click(function () {
            var type = $(this).val();
            var $UID = $("#spanTest").find(".EmployeeUID");
            var $START = $("#star_UID");
            if (type == "0" || type == "2") {
                $START.show();
                $START.parent().parent().show();
                $UID.attr("isnotnull", "1");
                //身份证号验证
                agencyVerify.regexCheckIDCard(null, "#txtUID", '请正确录入身份证18位，护照8至10位', true, "blur", null);
            }
            if (type == "1") {
                $START.parent().parent().hide();
                $START.hide();
                $UID.removeAttr("isnotnull");
                $UID.removeClass("checkError");
                $UID.next().remove();
            }
        });
     
        //当失去焦点时做非空验证
        employeeIndex.verify("#spanTest input[isnotnull=1]", "#spanTest select[isnotnull=1]", "#spanTest input[numlength=6]", "#spanTest input[issame=1]");
        //新增员工手机格式验证
        agencyVerify.mobileInput("#addStaff", "#txtAddMobile", false, "blur");
        //新增员工短号只能输入数字
        agencyVerify.greaterThanEqualZero("#txtCornet", false);
        //表单验证
        agencyVerify.nonnegativeIntInput("#addPackageCount");
        //验证员工编号格式
        agencyVerify.regexCheck(null, "#spanTest input[isUserNoSame=1]","^[a-zA-Z0-9]+$", "员工编号不能包含汉字和特殊符号", false, "blur");
        //验证用功编号是否重复
        agencyVerify.NoInputNameSame(null, "#spanTest input[isUserNoSame=1]", "blur", "员工编号重复", "/system/check-employeeNoExist", null);
        //验证员工手机号码
        //agencyVerify.NoInputNameSame(null, "#spanTest input[isusermobile=1]", "blur", "手机号码重复", "/system/check-employeeMobileExist", null);
        //身份证号验证
        agencyVerify.regexCheckIDCard(null, "#txtUID", '请正确录入身份证18位，护照8至10位', true, "blur", null);
        var myDate = employeeIndex.defaultDate(new Date());
        //初始化有效时间
        $("#spanTest").find(".EffectiveDate").val(myDate);

        //获取员工编号
        //$.AjaxAgency("/System/GetEmployeeNo", null, function (data) {
        //    if (data.indexOf("PPSZ")!=-1) {
        //        $("#spanTest").find(".EmployeeNo").val(data);
        //    }
        //    else {
        //        $.OKDialogAgency('<center>获取员工编号出错:' + data + '</center>');
        //    }
        //});
        //是否需要验证码
        var isShowSendCode = "1";
        var data = dataBind.getRealDataByType(98);
        if (data.length > 0) {
            for (var i = 0; i < data.length ; i++) {
                if (data[i].ItemText == "发送验证码开关") {
                    isShowSendCode = data[i].ExtendAttr;
                }
            }
        }
        if (isShowSendCode == "1") {
            $("#btnSendCode").show();
            $("#div_code").show();
            $("#txtCode").attr("isnotnull", "1");
        } else {
            $("#btnSendCode").hide();
            $("#div_code").hide();
            $("#txtCode").removeAttr("isnotnull");
        }

        $("#btnSendCode").unbind("click").click(function () {
            var m = $("#txtAddMobile");
            var n = $("#currentIdentifyName");
            var b = $("#btnSendCode");
            employeeIndex.SendCode(m, n, b);
        });
        $(".addEmployeeSubmit").removeAttr("disabled");
        if ($("#txtCode").next().attr("class") == "wrong") {
            $("#txtCode").nextAll().remove();
        }
        $("#txtCode").unbind("blur").bind("blur", function () {
            var b = $(".addEmployeeSubmit");
            var m = $("#txtAddMobile");
            var c = $("#txtCode");
            employeeIndex.MatchCode(b, m, c);
        });
        //初始化部门输入框
        EmployeePrompt.getDepartAndEmployeeByInputExcCode("currentIdentifyDeptId","txtAddEmployeeDepart", "txtAddEmployeeDepartKey", null, null, false, false, 1, null, "");
        //点击添加部门和角色的文本框
        employeeIndex.addDepartRole();
        //添加人员数据
        $('.addEmployeeSubmit').unbind('click');
        $(".addEmployeeSubmit").click(function () {
            $('.addEmployeeSubmit').attr("disabled", "disabled");
            //提交前先做验证
            if (employeeIndex.clickVerify("#spanTest .addEmployeeDepartKeyhidd", "#spanTest input[isUserNoSame=1]", "#spanTest input[isnotnull=1]", "#spanTest select[isnotnull=1]", "#spanTest input[numlength=6]", "#spanTest input[issame=1]", "#spanTest .checkError")) {
                if (isShowSendCode == "1") {
                    employeeIndex.MatchCode($(".addEmployeeSubmit"), $("#txtAddMobile"), $("#txtCode"));
                    if ($("#txtCode").next().attr("class") == "wrong") {
                        return false;
                    }
                }
                //当按钮点击后，按钮变灰别且不可用
                employeeIndex.moreSubmit($("#spanTest .addEmployeeSubmit"), "btn-red", "btn-gray", true);
                
                //获取多个部门和角色组合的值
                var departKeyId = [], departNames = [], roleKeyId = [];
                $("#spanTest .departAndRole").find(".info-list").each(function () {
                    departKeyId[departKeyId.length] = $(this).find(".addEmployeeDepartKeyhidd").val();
                    departNames[departNames.length] = $(this).find(".addEmployeeDeparthidd").val();
                    roleKeyId[roleKeyId.length] = $(this).find(".EmployeeRole").val()
                });
                //员工编号
                //var userNo = $("#spanTest").find(".EmployeeNo").val();
                //员工名称
                var userName = $("#spanTest").find(".EmployeeName").val();
                //手机号
                var mobile = $("#spanTest").find(".EmployeeMobile").val();
                //短号
                var cornet = $("#spanTest").find(".EmployeeCornet").val();
                var IsCheckIpLogin = $("#spanTest").find(".IsCheckIpLogin").is(':checked');
                var userType = $("input[name=UserType]:checked").val();
                var reqData = {
                   // "EmployeeNo": userNo,
                    "EmployeeName": userName,
                    "EmployeePWD": $("#spanTest").find(".EmployeePWD").val(),
                    "AdmPermission": $("#addAdmPermission").val(),
                    "PackageCount": $("#addPackageCount").val(),
                    "Mail": $("#spanTest").find(".Mail").val(),
                    "PhotoPath": $("#spanTest").find(".PhotoPath").val(),
                    "EmployeeDepart": departNames.join(","),
                    "EmployeeDepartKey": departKeyId.join(","),
                    "EffectiveDate": $("#spanTest").find(".EffectiveDate").val(),
                    "EmployeeRole": roleKeyId.join(","),
                    "IsCheckIpLogin": IsCheckIpLogin,
                    "Mobile": mobile,
                    "Cornet": cornet,
                    "UID": $("#spanTest").find(".EmployeeUID").val(),
                    "UserType": userType
                };
                $.AjaxAgency("/System/AddEmployee", reqData, function (data) {
                    var result = data.split('|');
                    if (result[0] == "True") {
                        if (result[1]) {
                            $.OKDialogAgency('<center>' + result[1] + '</center>', '提示', function () {
                                art.dialog.get("dialogProprietorEmployee").close();
                                window.location.reload();
                            });
                        }
                        else {
                            $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                                art.dialog.get("dialogProprietorEmployee").close();
                                window.location.reload();
                            });
                        }
                    }
                    else if (result[0] == "False") {
                        $.OKDialogAgency('<center>' + result[1] + '</center>', '提示', function () {
                            $(".addEmployeeSubmit").val("保存");
                        });
                    }
                    else {
                        $.OKDialogAgency('<center>' + result + '</center>');
                    }
                    $('.addEmployeeSubmit').removeAttr("disabled");
                    //点击完按钮处理完后变为正常状态
                    employeeIndex.moreSubmit($("#spanTest .addEmployeeSubmit"), "btn-gray", "btn-red", false);
                });
            } else {
                //验证不通过回复保存按钮
                $('.addEmployeeSubmit').removeAttr("disabled");
            }
        });
    });

    //根据选择的查询项调用不同的数据接口（条件搜索）
    $(".findType").change(function () {
        //每次选择查询类型先清除文本框的数据
        var findTypeValue = $(".findType").val();
        if (findTypeValue == "Ekey") {
            $(".employee").css("display", "block");
            $(".depart").css("display", "none");

            //调用员工的智能提示的接口
            $("#txtfindDepartName").val("");
            $("#txtfindDepartKey").val("");
        }
        else if (findTypeValue == "Dkey") {
            $(".employee").css("display", "none");
            $(".depart").css("display", "block");

            //调用部门智能提示的接口
            $("#txtfindEmployeeName").val("");
            $("#txtfindEmployeeKey").val("");
        }
    });

   
});


//处理多次按钮提交的问题
employeeIndex.moreSubmit = function (submitSeletor, removeClass, addClass, disabledValue) {

    //点击完按钮后处理不能点
    submitSeletor.attr("disabled", disabledValue);
    submitSeletor.removeClass(removeClass);
    submitSeletor.addClass(addClass);
};


//点击空白处隐藏
employeeIndex.showAndHide = function (selector, id, func, id2) {
    $(document).unbind("click");
    $(document).bind("click", function (e) {
        var divpanel = $("#" + id);
        var tempoint = divpanel.offset();
        if (e.pageX > (tempoint.left + divpanel.width()) || e.pageX < tempoint.left || e.pageY > (tempoint.top + divpanel.height()) || e.pageY < tempoint.top) {
            if (id2) {
                if (e.target != $(selector)[0] && e.target != $('#' + id2)) {
                    divpanel.hide();
                    if (func) {
                        func();
                    }
                    $(document).unbind("click");
                }
            } else {
                if (e.target != $(selector)[0]) {
                    divpanel.hide();
                    if (func) {
                        func();
                    }
                    $(document).unbind("click");
                }
            }

        }
    });
};

//选择时间控件的默认时间转换
employeeIndex.defaultDate = function (mydate) {

    var getFullYear = mydate.getFullYear();
    var getMonth = (mydate.getMonth() + 1);
    var getDate = mydate.getDate();
    var getHours = mydate.getHours();
    var getMinutes = mydate.getMinutes();

    if (getMonth.toString().length == 1) {
        getMonth = "0" + getMonth;
    }
    if (getDate.toString().length == 1) {
        getDate = "0" + getDate;
    }
    if (getHours.toString().length == 1) {
        getHours = "0" + getHours;
    }
    if (getMinutes.toString().length == 1) {
        getMinutes = "0" + getMinutes;
    }

    return getFullYear + "-" + getMonth + "-" + getDate;
};


//给下拉框动态绑定角色
employeeIndex.getRoles = function (selector, isBind, selectValue,isEditSelf) {
    //开始就加载所有的角色信息
    var reqedit = "0";
    if (isEditSelf == true) {
        reqedit = "1";
    }
    var reqData = {
        "isEditSelf": reqedit
    };
   
    $.AjaxAgency("/System/get-all-role", reqData, function (data) {
        if (data != null) {
            for (var k = 0; k < data.Result.length; k++) {
                selector.append('<option value="' + data.Result[k].KeyId + '">' + data.Result[k].RoleName + '</option>');
            }
        }
        else {
            $.OKDialogAgency('<center>' + data + '</center>');
        }
        //编辑时绑定值
        if (isBind) {
            selector.val(selectValue);
        }
    });

};

//Blur事件输入框验证  reserve Property
employeeIndex.verify = function (isnotnullSelector, isselectnotnullSelector, numlengthSelector, issanmeSelect) {

    //不能为空的验证
    agencyVerify.notNullInput(null, isnotnullSelector, true, "blur");
    //验证下拉框不能为空的验证
    agencyVerify.notNullInput(null, isselectnotnullSelector, true, "change");
    //验证输入的部门是否有重复的
    agencyVerify.NoInputSame(".departAndRole", issanmeSelect, "blur", "部门名称不能重复");

    //验证密码只能使6到14位
    agencyVerify.regexCheck(null, numlengthSelector, /^.{6,20}$/, "长度为6到20位", false, "blur");
};
//按钮Click事件验证
employeeIndex.clickVerify = function (ishiddenSelector, isnamesameSelector, isnotnullSelector, isselectnotnullSelector, numlengthSelector, issanmeSelect, ischeckSelector, EmployeeNo) {

    //验证密码位数
    $(isnotnullSelector).blur();
    //验证下拉框不能为空的验证
    $(isselectnotnullSelector).change();
    $(numlengthSelector).blur();
    $(issanmeSelect).blur();
    // $(isnamesameSelector).blur();
    if ($(ischeckSelector).length > 0) {
        return false;
    }
    else {

        if (!$(ishiddenSelector).val()) {
            $.OKDialogAgency('<center>请从下拉中选择部门！</center>');
            return false;
        }
        else {
            return true;
        }
    }
};

//格式化时间
employeeIndex.formatDate = function (value) {
    var date = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
    return employeeIndex.defaultDate(date);
};

//验证重置密码非空和密码与确认密码是否一致
employeeIndex.clickVerifyResetPWD = function (EmployeePWDSelector, confirmEmployeePWDSelector, isnotnullSelector) {
    $(isnotnullSelector).blur();
    confirmEmployeePWDSelector.blur(function () {
        if (confirmEmployeePWDSelector.val() != EmployeePWDSelector.val()) {
            if (confirmEmployeePWDSelector.next().attr("class") != "wrong") {
                confirmEmployeePWDSelector.after(agencyVerify.greatErrorHtml(confirmEmployeePWDSelector, '确认密码与密码不一致!'));
                confirmEmployeePWDSelector.addClass("checkError");
                confirmEmployeePWDSelector.focus();
            }
        }
        else {
            if (confirmEmployeePWDSelector.next().attr("class") == "wrong" && confirmEmployeePWDSelector.next().text() == "确认密码与密码不一致") {
                confirmEmployeePWDSelector.next().remove();
                $(confirmEmployeePWDSelector).removeClass("checkError");
                $(confirmEmployeePWDSelector).change();

            }
        }
    });
    if ($("#spanResetmployeePwd .checkError").length > 0) {
        return false;
    }
    else {
        return true;
    }
};
//Blur事件验证重置密码输入框
employeeIndex.verifyResetPWD = function (EmployeePWDSelector, confirmEmployeePWDSelector, isnotnullSelector) {
    agencyVerify.notNullInput(null, isnotnullSelector, false, "blur");
    if (EmployeePWDSelector) {
        var tempErrormsg = '确认密码与密码不一致!';
        $(EmployeePWDSelector).blur(function () {
            if ($(EmployeePWDSelector).val() != $(confirmEmployeePWDSelector).val() && $(confirmEmployeePWDSelector).next(".wrong").length <= 0) {
                $(confirmEmployeePWDSelector).addClass("checkError").after(agencyVerify.greatErrorHtml($(confirmEmployeePWDSelector), tempErrormsg));
            } else if ($(EmployeePWDSelector).val() == $(confirmEmployeePWDSelector).val() && $(confirmEmployeePWDSelector).next(".wrong").length > 0) {
                if ($(confirmEmployeePWDSelector).next(".wrong").html().indexOf(tempErrormsg) != -1) {
                    $(confirmEmployeePWDSelector).removeClass("checkError").next(".wrong").remove();
                }
            }
        }).focus(function () {
            $(EmployeePWDSelector).removeClass("checkError").next(".wrong").remove();
        });
    }
    if (confirmEmployeePWDSelector) {
        var tempErrormsg = '确认密码与密码不一致!';
        $(confirmEmployeePWDSelector).blur(function () {
            if ($(confirmEmployeePWDSelector).val() != $(EmployeePWDSelector).val() && $(confirmEmployeePWDSelector).next(".wrong").length <= 0) {
                $(confirmEmployeePWDSelector).addClass("checkError").after(agencyVerify.greatErrorHtml($(confirmEmployeePWDSelector), tempErrormsg));
            } else if ($(confirmEmployeePWDSelector).val() == $(EmployeePWDSelector).val() && $(confirmEmployeePWDSelector).next(".wrong").length > 0) {
                if ($(confirmEmployeePWDSelector).next(".wrong").html().indexOf(tempErrormsg) != -1) {
                    $(confirmEmployeePWDSelector).removeClass("checkError").next(".wrong").remove();
                }
            }
        }).focus(function () {
            $(confirmEmployeePWDSelector).removeClass("checkError").next(".wrong").remove();
        });
    }

};

//转移员工 切换标签方法 start
employeeIndex.ChangeTag = function () {
    //员工部门异动
    $("#spanTransferStaff .transferUser").click(function () {
        //切换之后先删除这种检验的的元素的class
        $("#spanTransferStaff select[isnotnull=1]").removeClass("checkError");
        //切换之后会清空选择的数据
        $("#spanTransferStaff .transferPropertys").val("");
        $("#spanTransferStaff .transferInquirys").val("");
        $("#spanTransferStaff .transferReals").val("");
        $("#spanTransferStaff .transferOnlyTrusts").val("");
        $("#spanTransferStaff .transferKeys").val("");
        $("#spanTransferStaff .transferMyTurns").val("");
        //动态绑定Tab页切换 员工转移框
        $("#spanTransferStaff #tabOrg").css("display", "none");
        $("#spanTransferStaff .defaultUser").css("display", "none");
        $("#spanTransferStaff .fastTransferUserAndDept").css("display", "none");
        $("#spanTransferStaff .userTransferdepat").css("display", "block");

        //员工转移按钮
        $("#spanTransferStaff .userTransferbtn").css("display", "block");
        $("#spanTransferStaff .resourceTransferbtn").css("display", "none");
        $("#spanTransferStaff .fastTransferresourcebtn").css("display", "none");
        //动态绑定Tab页切换
        var frameUrl = parent.$("#contentdiv #tabmenuiframe").attr("src");
        parent.$("#contentdiv #tabmenuiframe").attr("src", frameUrl.toString().split("?")[0] + "?userId=" + userKeyId + "&depatId=" + depatKeyId);
    });
    //转移资源
    $("#spanTransferStaff .transferResource").click(function () {
        $("#spanTransferStaff select[isnotnull=1]").removeClass("checkError");
        //切换之后会清空选择的数据
        $("#spanTransferStaff .transferPropertys").val("");
        $("#spanTransferStaff .transferInquirys").val("");
        $("#spanTransferStaff .transferReals").val("");
        $("#spanTransferStaff .transferOnlyTrusts").val("");
        $("#spanTransferStaff .transferKeys").val("");
        $("#spanTransferStaff .transferMyTurns").val("");
        //动态绑定Tab页切换
        //动态绑定Tab页切换 员工转移框
        $("#spanTransferStaff #tabOrg").css("display", "block");
        $("#spanTransferStaff .defaultUser").css("display", "none");
        $("#spanTransferStaff .fastTransferUserAndDept").css("display", "none");
        $("#spanTransferStaff .userTransferdepat").css("display", "none");
        //员工转移按钮
        $("#spanTransferStaff .userTransferbtn").css("display", "none");
        $("#spanTransferStaff .fastTransferresourcebtn").css("display", "none");
        $("#spanTransferStaff .resourceTransferbtn").css("display", "block");
        //动态绑定Tab页切换
        var frameUrl = parent.$("#contentdiv #tabmenuiframe").attr("src");
        parent.$("#contentdiv #tabmenuiframe").attr("src", frameUrl.toString().split("?")[0] + "?userId=" + userKeyId + "&depatId=" + depatKeyId);
    });
    //快速转移资源
    $("#spanTransferStaff .fastTransferResource").click(function () {
        $("#spanTransferStaff select[isnotnull=1]").removeClass("checkError");
        //切换之后会清空选择的数据
        $("#spanTransferStaff .transferPropertys").val("");
        $("#spanTransferStaff .transferInquirys").val("");
        $("#spanTransferStaff .transferReals").val("");
        $("#spanTransferStaff .transferOnlyTrusts").val("");
        $("#spanTransferStaff .transferKeys").val("");
        $("#spanTransferStaff .transferMyTurns").val("");
        //动态绑定Tab页切换
        //动态绑定Tab页切换 员工转移框
        $("#spanTransferStaff #tabOrg").css("display", "none");
        $("#spanTransferStaff .defaultUser").css("display", "none");
        $("#spanTransferStaff .fastTransferUserAndDept").css("display", "block");
        $("#spanTransferStaff .userTransferdepat").css("display", "none");
        //员工转移按钮
        $("#spanTransferStaff .userTransferbtn").css("display", "none");
        $("#spanTransferStaff .resourceTransferbtn").css("display", "none");
        $("#spanTransferStaff .fastTransferresourcebtn").css("display", "block");
    });
};
//转移员工 切换标签方法 end

//员工转移的验证
employeeIndex.verifyTransferUser = function (isnotnullSelector, isselectnotnullSelector) {
    //不能为空的验证
    agencyVerify.notNullInput(null, isnotnullSelector, true, "blur");
    //验证下拉框不能为空的验证
    agencyVerify.notNullInput(null, isselectnotnullSelector, true, "change");
};

//点击按钮员工转移的验证
employeeIndex.clickVerifyTransferUser = function (ishiddenSelector, isnotnullSelector, isselectnotnullSelector, transferDepat, allUserDepat, type) {
    //验证输入框不为空
    $(isnotnullSelector).blur();
    //验证下拉框不能为空的验证
    $(isselectnotnullSelector).change();
    if ($("#spanTransferStaff .checkError").length > 0) {
        return false;
    }
    else {
        if (transferDepat.length == 0) {
            $.OKDialogAgency('<center>无法转移，必须至少勾选一个需要被转移的部门！</center>');
            return false;
        }
        else if (type == "1") {
            if (!$(ishiddenSelector).val()) {
                $.OKDialogAgency('<center>请从下拉中选择异动业务员部门！</center>');
                return false;
            }
            else if ($.inArray($(ishiddenSelector).val(), allUserDepat) > -1) {
                $.OKDialogAgency('<center>选择的异动部门不能为该账号的现有部门！</center>');
                return false;
            }
            else {
                return true;
            }
        }
        else { return true; }
    }
};

//拼接checkbox展示该人的多个部门（角色）
employeeIndex.ShowUserDepatRole = function (userDepatRoleCheckSelector, userKeyId) {
    var reqData = {
        "userId": userKeyId
    };
    $.AjaxAgency("/System/get-user-depat-roles", reqData, function (data) {
        if (data.Flag) {
            if (data.Result != null && data.Result.length > 0) {
                $(userDepatRoleCheckSelector).empty();
                for (var i = 0; i < data.Result.length; i++) {
                    if (data.Result[i].DepartmentKeyId != undefined) {
                        if (!data.Result[i].LockUserDepatFlag) {
                            $(userDepatRoleCheckSelector).append("<label><input type=\"checkbox\" value=\"" + data.Result[i].DepartmentKeyId + "\" />[" + data.Result[i].DepartmentName + "]" + "[" + data.Result[i].RoleName + "]</label>");
                        }
                        else {
                            $(userDepatRoleCheckSelector).append("<label style=\"display:none\"><input type=\"checkbox\" value=\"" + data.Result[i].DepartmentKeyId + "\" />[" + data.Result[i].DepartmentName + "]" + "[" + data.Result[i].RoleName + "]</label>");
                        }
                    }
                }
            }
        }
        else {
            $.OKDialogAgency('<center>' + data + '</center>');
        }

    });
}

//根据部门过滤数据
employeeIndex.GetResourceDataByDepatKey = function () {
    //通过部门过滤资源数据
    $("#spanTransferStaff .userDepatRoleCheck").click(function () {
        var depats = [];
        $(this).find("input[type=checkbox]:checked").each(function () {
            depats[depats.length] = $(this).val();
        });
        depatKeyId = depats.join(",");
        $("#spanTransferStaff .transferDepatKeyIds").val(depatKeyId);
        //动态绑定Tab页切换
        var frameUrl = parent.$("#contentdiv #tabmenuiframe").attr("src");
        parent.$("#contentdiv #tabmenuiframe").attr("src", frameUrl.toString().split("?")[0] + "?userId=" + userKeyId + "&depatId=" + depatKeyId);
    });

};

//发送验证码
employeeIndex.SendCode = function (m,n,b) {
    var mobile = $(m).val();
    // $("#txtMobile").next().get(0).tagName;
    if ($(m).next().attr("class") == "wrong") {
        $(m).next().remove();
    }

    if (mobile == "") {
        var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>手机号不能为空<i></i></span></span>";
        $(m).after(html);
        return false;
    }
    var reg = /^[1][3456789][0-9]{9}$/;
    if (mobile.match(reg) == null) {
        var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>手机号格式错误<i></i></span></span>";
        $(m).after(html);
        return false;
    }
    employeeIndex.CountDown(b);
  
    //agencyVerify.mobileInput(null, $("#txtMobile"), true, "blur");
    var sicode = "1c1af135-d3b9-11e6-b969-00163e0ca245";
    var tplid = "554e62ec-d3b9-11e6-b969-00163e0ca245";
    var reqData = {
        "sicodde": sicode,
        "tplid": tplid,
        "mobile": 18601021432,
        "userName": $(n).val()
    };
    $.ajax({
        url: "/system/SendCode",
        data: {
            "sicodde": sicode,
            "tplid": tplid,
            "mobile": mobile,
            "userName": $(n).val()
        },
        success: function (data) {
            //alert(data);
        }
    });
};
//倒计时
var InterValObj;
employeeIndex.CountDown = function (e) {
     //timer变量，控制时间
    var  count = $("#countDownTime").val(); //间隔函数，1秒执行
    var curCount;//当前剩余秒数
    
    curCount = count;
    //设置button效果，开始计时
    $(e).attr("disabled", "true");
    $(e).css("cursor", "default");
    $(e).val("重新获取验证码(" + curCount + ")");
    InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器，1秒执行一次

    function SetRemainTime() {
        if (curCount == 0) {
            window.clearInterval(InterValObj);//停止计时器
            $(e).removeAttr("disabled");//启用按钮
            $(e).css("cursor", "pointer");
            $(e).val("重新获取验证码");
        }
        else {
            curCount--;
            $(e).val("重新获取验证码(" + curCount + ")");
        }
    }

};

//匹配code
employeeIndex.MatchCode = function (b,m,c) {
    //$(b).removeAttr("disabled");
    if ($(c).next().attr("class") == "wrong") {
        $(c).nextAll().remove();
    }
    if ($(c).hasClass("checkError")) {
        $(c).removeClass("checkError");
    }
    var arr = document.cookie.match(new RegExp("(^| )" + $(m).val() + "=([^;]*)(;|$)"));
    var code = "";
    if (arr != null)
        code = unescape(arr[2]);
    else
        code = "";
    if (code != $(c).val() || code=="") {
        var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>验证码不正确!<i></i></span></span>";
        $(c).after(html);
        $(b).attr("disabled", "disabled");
    } else {
        $(b).removeAttr("disabled");
    }
};

//编辑员工相关方法开始 start
employeeIndex.init = function () {

    //翻页初始化验证按钮的状态
    if ($("#treeTable .checkStaff:checked").length == 0) {
        employeeIndex.ModifyBtnStatus($('#userStatusModify i'), "icon-statusModify", "icon-statusModify-on");
        employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "edit-btn-gray", "btn-blue");
        employeeIndex.ModifyBtnStatus($(".clearfix #btn_syncUserInfo"), "edit-btn-gray", "btn-blue");
    }

    //员工全选/取消全选
    $("#treeTable .checkAll").click(function () {
        if ($("#treeTable .checkAll").attr("checked") == "checked") {
            $("#treeTable .checkStaff").each(function () {
                $(this).attr("checked", "true");
            });
            employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_syncUserInfo"), "btn-blue", "edit-btn-gray");
            // employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "btn-blue", "edit-btn-gray");
        }
        else {
            $("#treeTable .checkStaff").each(function () {
                $(this).removeAttr("checked");
            });
            employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "edit-btn-gray", "btn-blue");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "edit-btn-gray", "btn-blue");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "edit-btn-gray", "btn-blue");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_syncUserInfo"), "edit-btn-gray", "btn-blue");
            // employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
            employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "edit-btn-gray", "btn-blue");
        }
    });

    //选择后按钮状态变化
    $("#treeTable .checkStaff").click(function () {
        if ($("#treeTable .checkStaff:checked").length > 0) {
            //变化按钮状态
            employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "btn-blue", "edit-btn-gray");
            employeeIndex.ModifyBtnStatus($(".clearfix #btn_syncUserInfo"), "btn-blue", "edit-btn-gray");
            if ($("#treeTable .checkStaff:checked").length == 1) {
                employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "btn-blue", "edit-btn-gray");
            }
            else {
                employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
            }
        }
        else {
            if ($("#treeTable .checkStaff:checked").length == 0) {
                employeeIndex.ModifyBtnStatus($('#userStatusModify i'), "icon-statusModify", "icon-statusModify-on");
                $(".statusModify").hide();
                employeeIndex.ModifyBtnStatus($(".clearfix #userStatusModify"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix .transfer-staff"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix .del-staff"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionON"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix #btn_ADsPermisstionOFF"), "edit-btn-gray", "btn-blue");
                employeeIndex.ModifyBtnStatus($(".clearfix #btn_syncUserInfo"), "edit-btn-gray", "btn-blue");
            }
        }
    });

    //重置员工密码
    $("#treeTable .resetStaffPwd").bind("click", function () {
        //弹层显示拼接的元素
        $.dialog({
            id: "dialogResetEmployeePwd",
            lock: true,
            title: "重置密码",
            content: '<span id="spanResetmployeePwd">' + $(".resetStaffPWD").html() + '</span>'
        });
        //验证
        employeeIndex.verifyResetPWD($("#spanResetmployeePwd .EmployeePWD"), $("#spanResetmployeePwd .confirmEmployeePWD"), "#spanResetmployeePwd input[isnotnull=1]");


        //$("#spanResetmployeePwd .confirmEmployeePWD").focus(function() {
        //    if ($(this).next("span[class=wrong]").length > 0) {
        //        $(this).removeClass("checkError");
        //        $(this).next("span[class=wrong]").remove();
        //    }
        //});




        var userKeyId = $(this).attr("bbb");
        //保存重置的密码
        $(".btnResetPWD").click(function () {
            //根据key获取员工信息
            if (employeeIndex.clickVerifyResetPWD($("#spanResetmployeePwd .EmployeePWD"), $("#spanResetmployeePwd .confirmEmployeePWD"), "#spanResetmployeePwd input[isnotnull=1]")) {
                var url = "/System/reset-employeePWD";
                var reqData = {
                    "UserKeyId": userKeyId,
                    "UserPWD": $("#spanResetmployeePwd .EmployeePWD").val()
                };
                $.AjaxAgency(url, reqData, function (data) {
                    if (data == "OK") {
                        $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                            art.dialog.get("dialogResetEmployeePwd").close();
                            //window.location.reload();
                        });
                    }
                    else {
                        $.OKDialogAgency('<center>' + data + '</center>');
                    }
                });
            }
        });
    });

    //删除员工
    $("#treeTable .DeleteStaff").bind("click", function () {
        //获取删除的员工ID
        var userKeyId = $(this).attr("bbb");
        if (userKeyId == $('#currentIdentifyId').val()) {
            $.OKDialogAgency('<center>无法删除本人！</center>', '提示', function () {
                //window.location = "/system/employee";
            });
            return;
        }
        $.OKCancelDialogAgency("确认删除该员工在Agency中的账号么？", "删除员工", true, function () {
            var url = "/System/remove-singeemployee";
            var reqData = {
                "userKeyId": userKeyId
            };
            $.AjaxAgency(url, reqData, function (data) {
                if (data == "OK") {
                    $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                        window.location = "/system/employee";
                    });
                }
                else {
                    $.OKDialogAgency('<center>' + data + '</center>');
                }
            });
        }, null);
    });

    //转移员工 start
    $("#treeTable .TransferStaff").click(function () {
        //获取该员工的ID
        userKeyId = $(this).attr("bbb");
        //获取是否白名单5
        cchr = $(this).attr("cchr");
        $("#cchr").val(cchr);
        //获取当前登录人的ID
        var currentUserKeyId = $("#currentIdentifyId").val();
        if (userKeyId == currentUserKeyId)
        {
            $.OKDialogAgency('<center>您没有权限转移当前登录账号!</center>');
            return;
        }

        //获取员工姓名
        userName = $(this).parent().siblings().eq(2).text();
        //每次都先晴空已有的部门
        depatKeyId = "";
        var right = $(this).attr("right");
        var userDetp = $(this).attr("userDetp");
        var cchr = $(this).attr("cchr");

        if (right == "3" && userDetp == "0" && (cchr == "0" || cchr == "1")) {
            $.OKDialogAgency("无转移操作");
            return;
        }
        if (cchr == 5) {
            $("#UIDdiv").hide();
            $("#UIDdiv").find(".EmployeeUID").removeAttr("isnotnull");
            $("#UIDdiv").find(".EmployeeUID").removeClass("checkError");
            $("#UIDdiv").die("blur");
            $("#mobilediv").hide();
            $("#mobilediv").find(".Mobile").removeAttr("isnotnull");
            $("#mobilediv").find(".Mobile").removeClass("checkError");
            $("#mobilediv").die("blur");
        } else {
            $("#UIDdiv").show();
            $("#UIDdiv").find(".EmployeeUID").attr("isnotnull", "1");
            $("#mobilediv").show();
            $("#mobilediv").find(".Mobile").attr("isnotnull", "1");
        }
        if ((right == "3" && userDetp == "1" && (cchr == "2" || cchr == "3")) || (right == "1" && (cchr == "2" || cchr == "3"))) {
            $(".transferResource").show();
            $(".fastTransferResource").show();
            $("#tabOrg").css("display", "block");
            $(".defaultUser").css("display", "none");
            $(".fastTransferUserAndDept").css("display", "none");
            $(".userTransferdepat").css("display", "none");
            $("#radio_transferUser").removeAttr("checked");
            //员工转移按钮
            $(".userTransferbtn").css("display", "block");
            $(".resourceTransferbtn").css("display", "block");
            $(".fastTransferresourcebtn").css("display", "block");
        }
         //显示资源转移和快速转移
         if (right == "3" && userDetp == "1" && (cchr == "0" || cchr == "1") || (right == "1" && (cchr == "0" || cchr == "1"))) {
            $(".transferResource").show();
            $(".fastTransferResource").show();
            $("#tabOrg").css("display", "block");
            $(".defaultUser").css("display", "none");
            $(".fastTransferUserAndDept").css("display", "none");
            $(".userTransferdepat").css("display", "none");

            $(".transferUser").css("display", "none");
            $(".userTransferdepat").css("display", "none");
            //员工转移按钮
            $(".userTransferbtn").css("display", "none");
            $(".resourceTransferbtn").css("display", "block");
            $(".fastTransferresourcebtn").css("display", "none");
        }
        //else {
        //    $(".transferResource").show();
        //    $(".fastTransferResource").show();
        //    $("#tabOrg").css("display", "block");
        //    $(".defaultUser").css("display", "none");
        //    $(".fastTransferUserAndDept").css("display", "none");
        //    $(".userTransferdepat").css("display", "none");
        //    $("#radio_transferUser").removeAttr("checked");
        //    //员工转移按钮
        //    $(".userTransferbtn").css("display", "none");
        //    $(".resourceTransferbtn").css("display", "block");
        //    $(".fastTransferresourcebtn").css("display", "none");
        //}
        
        else if ($(this).attr("right") == "3" && userDetp == "0" && (cchr == "2" || cchr == "3")) {
            $(".transferResource").hide();
            $(".fastTransferResource").hide();
            $("#tabOrg").css("display", "none");
            $(".defaultUser").css("display", "none");
            $(".fastTransferUserAndDept").css("display", "none");
            $(".userTransferdepat").css("display", "block");

            $("#radio_transferUser").attr("checked", "checked");
            //员工转移按钮
            $(".userTransferbtn").css("display", "block");
            $(".resourceTransferbtn").css("display", "none");
            $(".fastTransferresourcebtn").css("display", "none");
        }
        else {
            //$(".transferResource").show();
            //$(".fastTransferResource").show();
            //$("#tabOrg").css("display", "block");
            //$(".defaultUser").css("display", "none");
            //$(".fastTransferUserAndDept").css("display", "none");
            //$(".userTransferdepat").css("display", "none");
            //$("#radio_transferUser").removeAttr("checked");
            ////员工转移按钮
            //$(".userTransferbtn").css("display", "none");
            //$(".resourceTransferbtn").css("display", "block");
            //$(".fastTransferresourcebtn").css("display", "none");

            $(".transferResource").show();
            $(".fastTransferResource").show();
            $(".transferUser").show();
            $("#tabOrg").css("display", "block");
            $(".defaultUser").css("display", "none");
            $(".fastTransferUserAndDept").css("display", "none");
            $(".userTransferdepat").css("display", "none");
      
            $("#radio_transferUser").removeAttr("checked");
            //员工转移按钮
            $(".userTransferbtn").css("display", "none");
            $(".resourceTransferbtn").css("display", "block");
            $(".fastTransferresourcebtn").css("display", "none");
        }
        //弹层显示拼接的元素
        $.dialog({
            id: "dialogTransferStaff",
            lock: true,
            title: "转移员工",
            width: 800,
            content: '<span id="spanTransferStaff">' + $("#transferData").html() + '</span>',
            close: function () { clearInterval(InterValObj); }
        });
        //初始化该用户的部门
        employeeIndex.ShowUserDepatRole("#spanTransferStaff .userDepatRoleCheck", userKeyId);
        //切换标签
        employeeIndex.ChangeTag();
        //动态绑定Tab页切换
        employeeIndex.initTransferStaffTab("titleid", "contentdiv");
        employeeIndex.transferStaffTab();

        var isShowSendCode="1";
        var data = dataBind.getRealDataByType(98);
        if (data.length > 0) {
            for (var i = 0; i < data.length ; i++) {
                if (data[i].ItemText == "发送验证码开关") {
                    isShowSendCode = data[i].ExtendAttr;
                }
            }
        }
        if (isShowSendCode == "1"&&cchr!=5) {
            var checkIsIdentifyingCode = function (k) {
                var transferDeptKeyId = $("#txtTransferDepartKey").val();
                if (transferDeptKeyId != "") {
                    var oldDeptKeyId = "";
                    $("#spanTransferStaff .userDepatRoleCheck input[type=checkbox]").each(function () {
                        oldDeptKeyId = $(this).val();
                    });
                    var reqKeyId = {
                        "oldDeptKeyId": oldDeptKeyId,
                        "newDeptKeyId": k
                    };
                    $.AjaxAgency("/org/check-department-issame-by-departmentno", reqKeyId, function (data) {
                        if (data) {
                            $("#divIdentifyingCode").hide();
                            $("#btnGetCode").hide();
                            $(".btnUserTransfer").removeAttr("disabled");
                            if ($(".identifyingCode").next().attr("class") == "wrong") {
                                $(".identifyingCode").nextAll().remove();
                            }
                        } else if (data == false) {
                            $("#divIdentifyingCode").show();
                            $("#btnGetCode").show();
                            $(".btnUserTransfer").removeAttr("disabled");
                            if ($(".identifyingCode").next().attr("class") == "wrong") {
                                $(".identifyingCode").nextAll().remove();
                            }
                        } else {
                            $.OKDialogAgency("<center>" + data + "</center>");
                        }
                    });

                }
            };
            //部门职能提示
            EmployeePrompt.getDepartAndEmployeeByInputExcCode("spanTransferStaff .userDepatRoleCheck input[type=checkbox]", "txtTransferDepartName", "txtTransferDepartKey", null, null, false, false, right, null, null, null, null, null,1,null, checkIsIdentifyingCode);
        } else {
            //部门职能提示
            EmployeePrompt.getDepartAndEmployeeByInputExcCode("spanTransferStaff .userDepatRoleCheck input[type=checkbox]", "txtTransferDepartName", "txtTransferDepartKey", null, null, false, false, right, null, null, null, null, null, 1, null, null);
        }
        //部门人员智能提示（用于快速转移资源功能）
        EmployeePrompt.getDepartAndEmployeeByInput("txtFastTransferDepartName", "txtFastTransferDepartKey", "txtFastTransferUserName", "txtFastTransferUserKey", false, true, 1, null, "请选择部门", true, true);
        //验证
        employeeIndex.verifyTransferUser("#spanTransferStaff input[isnotnull=1]", "#spanTransferStaff select[isnotnull=1]");
        //根据部门删选资源数据
        employeeIndex.GetResourceDataByDepatKey();

        //是否需要验证码
        $("#txtTransferDepartName").unbind("blur").bind("blur", function () {
            var transferDeptKeyId = $("#txtTransferDepartKey").val();
            if (transferDeptKeyId != "") {
                var oldDeptKeyId = "";
                $("#spanTransferStaff .userDepatRoleCheck input[type=checkbox]").each(function () {
                    if ($(this).attr("checked") == "checked") {
                        oldDeptKeyId = $(this).val();
                    }
                });
                var reqKeyId = {
                    "oldDeptKeyId": oldDeptKeyId,
                    "newDeptKeyId": transferDeptKeyId
                };
                //$.AjaxAgency("/org/check-department-issame-by-departmentno", reqKeyId, function (data) {
                //    if (data) {
                //        $("#divIdentifyingCode").hide();
                //    } else if (data == false) {
                //        $("#divIdentifyingCode").show();
                //    } else {
                //        $.OKDialogAgency("<center>"+data+"</center>");
                //    }
                //});
                
            } 
        });

        //员工异动
        $(".btnUserTransfer").click(function () {
            if ($("#divIdentifyingCode").is(':visible')) {
                if ($(".identifyingCode").val() == "") {
                    var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>验证码不能为空!<i></i></span></span>";
                    $(".identifyingCode").after(html);
                    return false;
                }
                employeeIndex.MatchCode($(".btnUserTransfer"), $("#txtMobile"), $(".identifyingCode"));
                if ($(".identifyingCode").next().attr("class") == "wrong") {
                    return false;
                }
            }
            var transferDepat = [], allUserDepat = [];
            $("#spanTransferStaff .userDepatRoleCheck input[type=checkbox]").each(function () {
                if ($(this).attr("checked") == "checked") {
                    transferDepat[transferDepat.length] = $(this).val();
                }
                allUserDepat[allUserDepat.length] = $(this).val();
            });
                //验证员工异动身份信息和电话
                $.ajax({
                    url: "/System/FindEmployeeByKey",
                    data: { "UserKeyId": userKeyId },
                    type: "json",
                    success: function (data) {
                        if (data.Flag) {
                            var uid = $("#spanTransferStaff").find(".EmployeeUID").val();
                            var cchr = $("#spanTransferStaff").find("#cchr").val();
                            var flag_UID, flag_Moible;
                            if (cchr != 5) {
                                if (uid != data.Result.UID && uid != "") {
                                    //$.OKDialogAgency("<center>身份证号不正确！</center>");
                                    var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>身份证号不正确<i></i></span></span>";
                                    $("#spanTransferStaff").find(".EmployeeUID").after(html);
                                    flag_UID = false;
                                } else {
                                    if ($("#spanTransferStaff").find(".EmployeeUID").next().attr("class") == "wrong") {
                                        $("#spanTransferStaff").find(".EmployeeUID").nextAll().remove();
                                    }
                                    if ($("#spanTransferStaff").find(".EmployeeUID").hasClass("checkError")) {
                                        $("#spanTransferStaff").find(".EmployeeUID").removeClass("checkError");
                                    }
                                    flag_UID = true;
                                }
                                var $mobile = $("#spanTransferStaff").find(".Mobile");
                                if ($mobile.val() != data.Result.Mobile && $mobile.val() != "") {
                                    //$.OKDialogAgency("<center>手机号不正确！</center>");
                                    var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>手机号不正确<i></i></span></span>";
                                    $mobile.after(html);
                                    flag_Moible = false;
                                } else {
                                    if ($mobile.next().attr("class") == "wrong") {
                                        $mobile.nextAll().remove();
                                    }
                                    if ($mobile.hasClass("checkError")) {
                                        $mobile.removeClass("checkError");
                                    }
                                    flag_Moible = true;
                                }
                                if (!flag_UID || !flag_Moible) {
                                    return false;
                                }
                            }
                            
                            if (employeeIndex.clickVerifyTransferUser("#spanTransferStaff #txtTransferDepartKey", "#spanTransferStaff input[isnotnull=1]", "#spanTransferStaff select[isnotnull=1]", transferDepat, allUserDepat, "1")) {
                                //禁用按钮防止多次提交
                                employeeIndex.moreSubmit($("#spanTransferStaff .btnUserTransfer"), "btn-red", "btn-gray", true);
                                $.OKCancelDialogAgency("确认完成[" + userName + "]的部门转移?点击确定后请等待", "部门转移", true, function () {
                                    var reqData = {
                                        "userKeyOId": userKeyId,
                                        //该账号异动到的新部门
                                        "transferDepartKeyId": $("#spanTransferStaff #txtTransferDepartKey").val(),
                                        "transferRoleKeyId": $("#spanTransferStaff .EmployeeRole").val(),
                                        //转移的资源(暂时未使用)
                                        "transferPropertyResources": $("#spanTransferStaff .transferPropertys").val(),
                                        "transferInquiryResources": $("#spanTransferStaff .transferInquirys").val(),
                                        "transferRealResources": $("#spanTransferStaff .transferReals").val(),
                                        "transferOnlyTrustResources": $("#spanTransferStaff .transferOnlyTrusts").val(),
                                        "transferKeyResources": $("#spanTransferStaff .transferKeys").val(),
                                        "transferMyTurnResources": $("#spanTransferStaff .transferMyTurns").val(),
                                        //业绩分成数据
                                        "transferperformancesResources": $("#spanTransferStaff .transferperformances").val(),
                                        "transferTrustRecordsResources": $("#spanTransferStaff .transferTrustRecords").val(),
                                        //是否默认转移为上级领导
                                        "isDefaultManagerUser": $("#spanTransferStaff #isDefaultManagerUser").attr("checked"),
                                        //需要异动的部门
                                        "transferDepatKeyIds": transferDepat.join(","),
                                        //资源全部带走
                                        "transferMyself": $("#spanTransferStaff #transferMyself").attr("checked")
                                    };
                                    $.AjaxAgency("/System/save-user-transfer", reqData, function (data) {
                                        if (data == "OK") {
                                            $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                                                art.dialog.get("dialogTransferStaff").close();
                                            });
                                        }
                                        else {
                                            $.OKDialogAgency('<center>' + data + '</center>');
                                        }
                                        //禁用按钮防止多次提交
                                        employeeIndex.moreSubmit($("#spanTransferStaff .btnUserTransfer"), "btn-gray", "btn-red", false);
                                    });
                                }, function () {//禁用按钮防止多次提交
                                    employeeIndex.moreSubmit($("#spanTransferStaff .btnUserTransfer"), "btn-gray", "btn-red", false);
                                });
                            }
                        } else {
                            $.OKDialogAgency("<center>获取验证信息失败！</center>");
                            return false;
                        }
                    },
                    error: function () {
                        $.OKDialogAgency("<center>获取验证信息失败！</center>");
                        return false;
                    }
                });
            
            //if (employeeIndex.clickVerifyTransferUser("#spanTransferStaff #txtTransferDepartKey", "#spanTransferStaff input[isnotnull=1]", "#spanTransferStaff select[isnotnull=1]", transferDepat, allUserDepat, "1")) {
            //    //禁用按钮防止多次提交
            //    employeeIndex.moreSubmit($("#spanTransferStaff .btnUserTransfer"), "btn-red", "btn-gray", true);
            //    $.OKCancelDialogAgency("确认完成[" + userName + "]的部门转移?点击确定后请等待", "部门转移", true, function () {
            //        var reqData = {
            //            "userKeyOId": userKeyId,
            //            //该账号异动到的新部门
            //            "transferDepartKeyId": $("#spanTransferStaff #txtTransferDepartKey").val(),
            //            "transferRoleKeyId": $("#spanTransferStaff .EmployeeRole").val(),
            //            //转移的资源(暂时未使用)
            //            "transferPropertyResources": $("#spanTransferStaff .transferPropertys").val(),
            //            "transferInquiryResources": $("#spanTransferStaff .transferInquirys").val(),
            //            "transferRealResources": $("#spanTransferStaff .transferReals").val(),
            //            "transferOnlyTrustResources": $("#spanTransferStaff .transferOnlyTrusts").val(),
            //            "transferKeyResources": $("#spanTransferStaff .transferKeys").val(),
            //            "transferMyTurnResources": $("#spanTransferStaff .transferMyTurns").val(),
            //            //业绩分成数据
            //            "transferperformancesResources": $("#spanTransferStaff .transferperformances").val(),
            //            //是否默认转移为上级领导
            //            "isDefaultManagerUser": $("#spanTransferStaff #isDefaultManagerUser").attr("checked"),
            //            //需要异动的部门
            //            "transferDepatKeyIds": transferDepat.join(","),
            //            //资源全部带走
            //            "transferMyself": $("#spanTransferStaff #transferMyself").attr("checked")
            //        };
            //        $.AjaxAgency("/System/save-user-transfer", reqData, function (data) {
            //            if (data == "OK") {
            //                $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
            //                    art.dialog.get("dialogTransferStaff").close();
            //                });
            //            }
            //            else {
            //                $.OKDialogAgency('<center>' + data + '</center>');
            //            }
            //            //禁用按钮防止多次提交
            //            employeeIndex.moreSubmit($("#spanTransferStaff .btnUserTransfer"), "btn-gray", "btn-red", false);
            //        });
            //    }, function () {//禁用按钮防止多次提交
            //        employeeIndex.moreSubmit($("#spanTransferStaff .btnUserTransfer"), "btn-gray", "btn-red", false);
            //    });
            //}
        });
        //关闭
        $(".btnResourceCancel").click(function () {
            art.dialog.get("dialogTransferStaff").close();
        });

        //资源转移
        $(".btnResourceTransfer").click(function () {
            var transferDepat = [], allUserDepat = [];
            $("#spanTransferStaff .userDepatRoleCheck input[type=checkbox]").each(function () {
                if ($(this).attr("checked") == "checked") {
                    transferDepat[transferDepat.length] = $(this).val();
                }
                allUserDepat[allUserDepat.length] = $(this).val();
            });
            if (employeeIndex.clickVerifyTransferUser("", "", "", transferDepat, allUserDepat, "2")) {
                //禁用按钮防止多次提交
                employeeIndex.moreSubmit($("#spanTransferStaff .btnResourceTransfer"), "btn-red", "btn-gray", true);
                $.OKCancelDialogAgency("确认完成[" + userName + "]的资源转移?点击确定后请等待", "资源转移", true, function () {
                    var transferDepat = [];
                    $("#spanTransferStaff .userDepatRoleCheck input[type=checkbox]").each(function () {
                        if ($(this).attr("checked") == "checked") {
                            transferDepat[transferDepat.length] = $(this).val();
                        }
                    });
                    var reqData = {
                        "userKeyOId": userKeyId,
                        "transferPropertyResources": $("#spanTransferStaff .transferPropertys").val(),
                        "transferInquiryResources": $("#spanTransferStaff .transferInquirys").val(),
                        "transferRealResources": $("#spanTransferStaff .transferReals").val(),
                        "transferOnlyTrustResources": $("#spanTransferStaff .transferOnlyTrusts").val(),
                        "transferKeyResources": $("#spanTransferStaff .transferKeys").val(),
                        "transferMyTurnResources": $("#spanTransferStaff .transferMyTurns").val(),
                        "transferAdvertResources": $("#spanTransferStaff .transferAdvertRecords").val(),
                        //业绩分成数据
                        "transferperformancesResources": $("#spanTransferStaff .transferperformances").val(),
                        "transferTrustRecordsResources": $("#spanTransferStaff .transferTrustRecords").val(),
                        //是否默认转移为上级领导
                        "isDefaultManagerUser": $("#spanTransferStaff #isDefaultManagerUser").attr("checked"),
                        "transferDepatKeyIds": transferDepat.join(",")
                    };
                    $.AjaxAgency("/System/save-user-resource-transfer", reqData, function (data) {
                        if (data == "OK") {
                            $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                                //art.dialog.get("dialogTransferStaff").close(); 
                                //window.location.reload();
                                //清空选择的数据
                                $("#spanTransferStaff [type='hidden']").val("");
                                $("#spanTransferStaff #tabmenuiframe").attr('src', $('#spanTransferStaff #tabmenuiframe').attr('src'));                                                               
                            });
                        }
                        else {
                            $.OKDialogAgency('<center>' + data + '</center>');
                        }
                        //启用按钮防止多次提交
                        employeeIndex.moreSubmit($("#spanTransferStaff .btnResourceTransfer"), "btn-gray", "btn-red", false);
                    });
                }, function () {//禁用按钮防止多次提交
                    employeeIndex.moreSubmit($("#spanTransferStaff .btnResourceTransfer"), "btn-gray", "btn-red", false);
                });
            }
        });
        //关闭
        $(".btnUserCancel").click(function () {
            art.dialog.get("dialogTransferStaff").close();
            clearInterval(InterValObj);
        });

        //快速转移资源
        $(".btnFastResourceTransfer").click(function () {
            var transferDepat = [], allUserDepat = [];
            $("#spanTransferStaff .userDepatRoleCheck input[type=checkbox]").each(function () {
                if ($(this).attr("checked") == "checked") {
                    transferDepat[transferDepat.length] = $(this).val();
                }
                allUserDepat[allUserDepat.length] = $(this).val();
            });
            if (employeeIndex.clickVerifyTransferUser("#spanTransferStaff #txtFastTransferUserKey", "", "", transferDepat, allUserDepat, "1")) {
                //禁用按钮防止多次提交
                employeeIndex.moreSubmit($("#spanTransferStaff .btnFastResourceTransfer"), "btn-red", "btn-gray", true);
                $.OKCancelDialogAgency("确认完成[" + userName + "]的资源转移?点击确定后请等待", "资源转移", true, function () {
                    var transferDepat = [];
                    $("#spanTransferStaff .userDepatRoleCheck input[type=checkbox]").each(function () {
                        if ($(this).attr("checked") == "checked") {
                            transferDepat[transferDepat.length] = $(this).val();
                        }
                    });
                    var reqData = {
                        //被转移的员工ID
                        "userKeyOId": userKeyId,
                        //被转移员工所在部门的ID
                        "transferDepatKeyIds": transferDepat.join(","),
                        //转移到的员工ID
                        "fasttransferUserKeyId": $(".fastTransferUserAndDept #txtFastTransferUserKey").val(),
                        //转移到的员工所在部门ID
                        "fasttransferDeptKeyId": $(".fastTransferUserAndDept #txtFastTransferDepartKey").val()
                    };
                    $.AjaxAgency("/System/save-fast-transfer-resource", reqData, function (data) {
                        if (data == "OK") {
                            $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                                art.dialog.get("dialogTransferStaff").close();
                                // window.location.reload();
                            });
                        }
                        else {
                            $.OKDialogAgency('<center>' + data + '</center>');
                        }
                        //禁用按钮防止多次提交
                        employeeIndex.moreSubmit($("#spanTransferStaff .btnFastResourceTransfer"), "btn-gray", "btn-red", false);
                    });
                }, function () {//禁用按钮防止多次提交
                    employeeIndex.moreSubmit($("#spanTransferStaff .btnFastResourceTransfer"), "btn-gray", "btn-red", false);
                });
            }
        });
        //关闭
        $(".btnFastResourceCancel").click(function () {
            art.dialog.get("dialogTransferStaff").close();
        });

        //发送验证码
        $("#btnGetCode").click(function () {
            var mobile = $("#txtMobile").val();
            // $("#txtMobile").next().get(0).tagName;
            if ($("#txtMobile").next().attr("class") == "wrong") {
                $("#txtMobile").next().remove();
            }

            if (mobile == "") {
                var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>手机号不能为空<i></i></span></span>";
                $("#txtMobile").after(html);
                return false;
            }
            var reg = /^[1][3456789][0-9]{9}$/;
            if (mobile.match(reg) == null) {
                var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>手机号格式错误<i></i></span></span>";
                $("#txtMobile").after(html);
                return false;
            }
            $.AjaxAgency("/System/FindEmployeeByKey", { "UserKeyId": userKeyId }, function (data) {
                if (data.Flag) {
                    //var mobile = $("#spanTransferStaff").find(".Mobile").val();
                    if (mobile != data.Result.Mobile) {
                        var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>手机号码不正确!<i></i></span></span>";
                        $("#txtMobile").after(html);
                        return false;
                    } else {
                        employeeIndex.CountDown("#btnGetCode");
                        $.ajax({
                            url: "/system/SendCode",
                            data: {
                                "mobile": mobile,
                                "userName": $("#currentIdentifyName").val()
                            },
                            success: function (data) {
                                //alert(data);
                            }
                        });
                    }
                } else {
                    $.OKDialogAgency("<center>获取验证信息失败！</center>");
                    return false;
                }
            });
           
        });

        $(".btnUserTransfer").removeAttr("disabled");
        if ($(".identifyingCode").next().attr("class") == "wrong") {
            $(".identifyingCode").nextAll().remove();
        }
        $(".identifyingCode").unbind().bind("blur", function () {
            if ($(".identifyingCode").next().attr("class") == "wrong") {
                $(".identifyingCode").nextAll().remove();
            }
            var arr = document.cookie.match(new RegExp("(^| )" + $("#txtMobile").val() + "=([^;]*)(;|$)"));
            var code="";
            if (arr != null) 
                code= unescape(arr[2]); 
            else
                code = "";

            if (code != $(".identifyingCode").val() || code=="") {
                var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>验证码不正确!<i></i></span></span>";
                $(".identifyingCode").after(html);
                $(".btnUserTransfer").attr("disabled", "disabled");;
            } else {
                $(".btnUserTransfer").removeAttr("disabled");
            }
        });
    });
    //转移员工 end

  
    //编辑员工信息具体方法
    //初始化编辑员工方法
    $("#treeTable .editStaff").bind("click", function () {
        var isupdateuid = $(this).attr("isupdateuid");
        var haswhitelist = $(this).attr("haswhitelist");
        var iscchr = $(this).attr("haswhitelist");
        var cchr = $(this).attr("cchr");
        //弹层显示拼接的元素
        $.dialog({
            id: "dialogProprietorEditEmployee",
            lock: true,
            title: "编辑员工",
            content: '<span id="spanEditemployee">' + $(".editEmployee").html() + '</span>'
        });
        //根据key获取员工信息
        var url = "/System/FindEmployeeByKey";
        var reqData = {
            "UserKeyId": $(this).attr("bbb")
        };
        var selectuserkeyid=$(this).attr("bbb");
        var currentuserkeyid = $("#currentIdentifyId").val();
        //判断用户类型
        var $uid = $("#spanEditemployee").find(".editEmployeeUID");
        //身份证验证
        agencyVerify.regexCheckIDCard(null, "#txtUID", '请正确录入身份证18位，护照8至10位', true, "blur", null);
        var oldmobile = "";
        $("#spanEditemployee input[name=EditUserType]").click(function () {
            var type = $(this).val();
            var $START = $("#editstar_UID");
            if (type == "0" || type == "2") {
                $START.show();
                $START.parent().parent().show();
                $uid.attr("isnotnull", "1");
                //身份证验证
                agencyVerify.regexCheckIDCard(null, "#txtUID", '请正确录入身份证18位，护照8至10位', true, "blur", null);
                if (type == "0") {
                    $("#hidden_usertype_iscchr").val("3");//跑盘
                } else {
                    $("#hidden_usertype_iscchr").val("0");//跑盘
                }
            }
            if (type == "1") {
                $START.hide();
                $START.parent().parent().hide();
                $uid.removeAttr("isnotnull");
                $uid.removeClass("checkError");
                $uid.next().remove();
                $("#txtUID").die("blur");
                $("#hidden_usertype_iscchr").val("5");//白名单
            }
        });
        
        $.AjaxAgency(url, reqData, function (data) {
            if (data.Flag) {
                oldmobile = data.Result.Mobile;
                $("#spanEditemployee").find(".editEmployeeKeyId").val(data.Result.KeyId);
                $("#spanEditemployee").find(".editEmployeeNo").val(data.Result.EmployeeNo);
                $("#spanEditemployee").find(".editStutas").val(data.Result.Status);
                $("#spanEditemployee").find(".editEmployeeName").val(data.Result.EmployeeName);
                $("#spanEditemployee").find(".editMobile").val(data.Result.Mobile);
                $("#spanEditemployee").find(".editCornet").val(data.Result.Cornet);
                $("#spanEditemployee").find(".editEmployeeUID").val(data.Result.UID);
                // $("#spanEditemployee").find(".editEmployeePWD").val(data.Result.UserPWD);
                $("#spanEditemployee").find(".editMail").val(data.Result.Mail);
                $("#spanEditemployee").find(".editPhotoPath").val(data.Result.PhotoPath);
                $("#spanEditemployee").find(".editEmployeeImg").attr("src", data.Result.PhotoPath);
                $("#spanEditemployee").find(".IsCheckIpLogin").attr("checked", data.Result.IsCheckIpLogin);
                $("#editAdmPermission").val(data.Result.AdmPermission);
                $("#editPackageCount").val(data.Result.PackageCount);
                $("#txtUID").val(data.Result.UID);
                var iscchr = data.Result.IsCCHR;
                switch (iscchr) {
                    case 0:
                    case 1:
                        $("#editusertype2").attr("checked", "checked");
                        //正式员工
                        break;
                    case 2:
                    case 3:
                    case 4:
                        $("input[name=EditUserType]:first").attr("checked", "checked");
                        //跑盘账号
                        break;
                    default:
                        //白名单
                        $("#editusertype1").attr("checked", "checked");
                        break;
                }
                $("#hidden_usertype_iscchr").val(iscchr);//跑盘
                if (iscchr == 0 || iscchr == 1) {
                    $("#spanEditemployee").find(".editStutas").attr("disabled", "disabled");
                    $("#spanEditemployee").find(".editEmployeeName").attr("readonly", "readonly");
                    $("#spanEditemployee").find(".editMail").attr("readonly", "readonly");
                    $("#spanEditemployee").find(".editPhotoPath").attr("readonly", "readonly");
                    $("#spanEditemployee").find(".EmployeeLackFlag").attr("disabled", "disabled");
                    $("#spanEditemployee").find(".EffectiveDate").attr("disabled", "disabled");
                    $("#spanEditemployee").find(".IsCheckIpLogin").attr("disabled", "disabled");
                    $("#divadddeprole").hide();
                } else {
                    $("#spanEditemployee").find(".editStutas").removeAttr("disabled");
                    $("#spanEditemployee").find(".editEmployeeName").removeAttr("readonly");
                    $("#txtUID").removeAttr("readonly");
                    $("#divadddeprole").show();
                }
                if (data.Result.IsCCHR == 5) {
                    $("#editstar_UID").hide();
                    $("#editstar_UID").parent().parent().hide();
                    $uid.removeAttr("isnotnull");
                    $uid.removeClass("checkError");
                    $uid.next().remove();
                    $("#txtUID").die("blur");
                } else {
                    $("#editstar_UID").show();
                    $("#editstar_UID").parent().parent().show();
                    $uid.attr("isnotnull", "1");
                    agencyVerify.regexCheckIDCard(null, "#txtUID", '请正确录入身份证18位，护照8至10位', true, "blur", null);
                }
                if (haswhitelist == "0") {
                    $("input[name=EditUserType]:first").attr("disabled", "disabled");
                    $("#editusertype1").attr("disabled", "disabled");
                } else {
                    $("input[name=EditUserType]:first").removeAttr("disabled");
                    $("#editusertype1").removeAttr("disabled");
                }
                
                //调用一个拼接多个部门角色的方法
                for (var k = 0; k < data.Result.DeptRoleGroups.length; k++) {
                    if (k >= 0) {
                        var rowHtml = '<div class="info-list clearfix h26lh26"><label class="l"><strong class="public w86"><em class="star">*</em>所属部门：</strong> '
                        + '<input type="text" class="ipt addEmployeeDeparthidd w115" isnotnull="1" issame="1" id="txtEditEmployeeDepart' + k + '"  readonly="true"/></label> '
                        + '<input type="hidden" class="addEmployeeDepartKeyhidd" id="txtEditEmployeeDepartKey' + k + '" />'
                        + '<strong class="public w86"><em class="star">*</em>角　　色：</strong> '
                        + '<select class="select EmployeeRole" isnotnull="1" style="width:141px;" id="editEmployeeRole' + k + '">'
                        + ' <option value="">请选择</option> </select>'
                        + '\n\r'
                        + '<select class="select w69 EmployeeLackFlag" name="EmployeeLackFlag">'
                        if (data.Result.DeptRoleGroups[k].LockFlag == 0) {
                            rowHtml = rowHtml + '<option value="0" selected >未锁定</option><option value="1">锁定</option>'
                        }
                        if (data.Result.DeptRoleGroups[k].LockFlag == 1) {
                            rowHtml = rowHtml + '<option value="1" selected >锁定</option><option value="0">未锁定1</option>'
                        }
                        rowHtml = rowHtml + '</select>'
                        + '\n\r'
                        //rowHtml = rowHtml + '<i class="delinfo" onclick="employeeIndex.DelDepartAndRole(this);"></i>'
                        rowHtml = rowHtml + ' <input type="hidden" id="userKeyId" value="' + reqData.UserKeyId + '" /> <input type="hidden" id="depatKeyId" value="' + data.Result.DeptRoleGroups[k].DeptKeyId + '" /> </div>'

                        $("#spanEditemployee").find(".departAndRole").append(rowHtml);
                        
                        //将动态添加的角色绑定数据
                        if (selectuserkeyid == currentuserkeyid) {//编辑本人
                            employeeIndex.getRoles($("#spanEditemployee").find("#editEmployeeRole" + k + ""), true, data.Result.DeptRoleGroups[k].RoleKeyId, true);
                        } else {
                            employeeIndex.getRoles($("#spanEditemployee").find("#editEmployeeRole" + k + ""), true, data.Result.DeptRoleGroups[k].RoleKeyId, false);
                        }

                        $("#spanEditemployee").find("#txtEditEmployeeDepart" + k + "").val(data.Result.DeptRoleGroups[k].DeptName);
                        $("#spanEditemployee").find("#txtEditEmployeeDepartKey" + k + "").val(data.Result.DeptRoleGroups[k].DeptKeyId);
                    }
                }
                $("#spanEditemployee").find(".EffectiveDate").val(employeeIndex.formatDate(data.Result.EffectiveDate));
            }
            else {
                //弹层显示拼接的元素
                $.dialog({
                    id: "dialogProprietorEditEmployee",
                    lock: true,
                    content: '<span id="spanEditemployee">' + $(".editEmployee").html() + '</span>'
                });
            }
            //表单验证
            agencyVerify.nonnegativeIntInput("#editPackageCount");
            //验证员工编号格式
            agencyVerify.regexCheck(null, "#spanEditemployee input[isUserNoSame=1]", "^[a-zA-Z0-9]+$", "员工编号不能包含汉字和特殊符号", false, "blur");
            //验证用功编号是否重复
            agencyVerify.NoInputNameSame(null, "#spanEditemployee input[isUserNoSame=1]", "blur", "员工编号重复", "/system/check-employeeNoExist", data.Result.EmployeeNo);
            //身份证验证
            agencyVerify.regexCheckIDCard(null, "#txteditUID", '请正确录入身份证18位，护照8至10位', true, "blur", null);
        });
        //初始化部门输入框(第一个框的)
        EmployeePrompt.getDepartAndEmployeeByInput("txtEditEmployeeDepart", "txtEditEmployeeDepartKey", null, null, false, false, 1, null, "");

        //动态添加部门和角色
        employeeIndex.editDepartRole();

        //当失去焦点时做非空验证
        employeeIndex.verify("#spanEditemployee input[isnotnull=1]", "#spanEditemployee select[isnotnull=1]", "#spanEditemployee input[numlength=6]", "#spanEditemployee input[issame=1]");
        //编辑用户手机格式验证
        agencyVerify.mobileInput("#editEmployee", "#txtMobile", false, "blur");
        //编辑短号只能输入数字
        agencyVerify.greaterThanEqualZero("#txtCornet", false);
        
        //是否需要验证码
        var isShowSendCode = "1";
        var data = dataBind.getRealDataByType(98);
        if (data.length > 0) {
            for (var i = 0; i < data.length ; i++) {
                if (data[i].ItemText == "发送验证码开关") {
                    isShowSendCode = data[i].ExtendAttr;
                }
            }
        }
        var showFlag = "0";
        $("#txtMobile").bind("blur", function() {
            var newmobile = $("#txtMobile").val();
            if (isShowSendCode == "1" && cchr != 5) {
                if (oldmobile != newmobile) {
                    $("#btnEditSendCode").show();
                    $("#div_editcode").show();
                    showFlag = "1";
                } else {
                    $("#btnEditSendCode").hide();
                    $("#div_editcode").hide();
                    showFlag = "0";
                }
            } else {
                $("#btnEditSendCode").hide();
                $("#div_editcode").hide();
                showFlag = "0";
            }
            if ($("#txtEditCode").next().attr("class") == "wrong") {
                $("#txtEditCode").nextAll().remove();
            }
            if ($("#txtEditCode").hasClass("checkError")) {
                $("#txtEditCode").removeClass("checkError");
            }
            $(".btneditEmployee").removeAttr("disabled");
        });
        $("#btnEditSendCode").unbind("click").click(function () {
            var m = $("#txtMobile");
            var n = $("#currentIdentifyName");
            var b = $("#btnEditSendCode");
            employeeIndex.SendCode(m, n, b);
        });
        $(".btneditEmployee").removeAttr("disabled");
        if ($("#txtEditCode").next().attr("class") == "wrong") {
            $("#txtEditCode").nextAll().remove();
        }
        $("#txtEditCode").unbind("blur").bind("blur", function () {
            var b = $(".btneditEmployee");
            var m = $("#txtMobile");
            var c = $("#txtEditCode");
            employeeIndex.MatchCode(b, m, c);
        });
        //提交修改的人员信息
        $("#spanEditemployee .btneditEmployee").click(function () {
            $("#spanEditemployee .btneditEmployee").attr("disabled", "disabled");
            if ($("#btnEditSendCode").is(':visible')) {
                if ($("#txtEditCode").val() == "") {
                    var html = "<span class='wrong'><span style='left: -140px; top: -30px;'>验证码不能为空!<i></i></span></span>";
                    $("#txtEditCode").after(html);
                    return false;
                }
                employeeIndex.MatchCode($(".btneditEmployee"), $("#txtMobile"), $("#txtEditCode"));
                if ($("#txtEditCode").next().attr("class") == "wrong") {
                    return false;
                }
            }
            //if ($("#spanEditemployee").find(".wrong:visible").length == 0 && $("#spanEditemployee").find("[isnotnull]").val() != -1) {
            //    $(this).attr("disabled", "disabled");
            //}
            $("#txtEditCode").blur();
            if (employeeIndex.clickVerify("#spanEditemployee .addEmployeeDepartKeyhidd", "#spanEditemployee input[isUserNoSame=1]", "#spanEditemployee input[isnotnull=1]", "#spanEditemployee select[isnotnull=1]", "#spanEditemployee input[numlength=6]", "#spanEditemployee input[issame=1]", "#spanEditemployee .checkError")) {
            
                employeeIndex.moreSubmit($("#spanEditemployee .btneditEmployee"), "btn-red", "btn-gray", true);

                //获取多个部门和角色组合的值
                var departKeyId = [], departNames = [], roleKeyId = [], roleName = [], lockFlags = [];
                $("#spanEditemployee .departAndRole").find(".info-list").each(function () {
                    departKeyId[departKeyId.length] = $(this).find(".addEmployeeDepartKeyhidd").val();
                    departNames[departNames.length] = $(this).find(".addEmployeeDeparthidd").val();
                    roleKeyId[roleKeyId.length] = $(this).find(".EmployeeRole").val();
                    roleName[roleName.length] = $(this).find(".EmployeeRole").find("option:selected").text();
                    lockFlags[lockFlags.length] = $(this).find(".EmployeeLackFlag").val();
                });
                var url = "/System/ModifyEmployee";
                var reqData = {
                    "UserKeyId": $("#spanEditemployee").find(".editEmployeeKeyId").val(),
                    "EmployeeNo": $("#spanEditemployee").find(".editEmployeeNo").val(),
                    "EmployeeName": $("#spanEditemployee").find(".editEmployeeName").val(),
                    "AdmPermission": $("#editAdmPermission").val(),
                    "PackageCount": $("#editPackageCount").val(),
                    // "EmployeePWD": $("#spanEditemployee").find(".editEmployeePWD").val(),
                    "Mail": $("#spanEditemployee").find(".editMail").val(),
                    "PhotoPath": $("#spanEditemployee").find(".editPhotoPath").val(),
                    "EmployeeDepart": departNames.join(","),
                    "EmployeeDepartKey": departKeyId.join(","),
                    "EffectiveDate": $("#spanEditemployee").find(".EffectiveDate").val(),
                    "EmployeeRole": roleKeyId.join(","),
                    "EmployeeRoleName": roleName.join(","),
                    "UserStutas": $("#spanEditemployee").find(".editStutas").val(),
                    "lockFlag": lockFlags.join(","),
                    "IsCheckIpLogin": $("#spanEditemployee").find(".IsCheckIpLogin").is(':checked'),
                    "Mobile": $("#spanEditemployee").find(".editMobile").val(),
                    "Cornet": $("#spanEditemployee").find(".editCornet").val(),
                    "UserType": $("#hidden_usertype_iscchr").val(),//$("input[name=EditUserType]:checked").val(),
                    "UID": $("#spanEditemployee").find(".editEmployeeUID").val()
                };
                $.AjaxAgency(url, reqData, function (data) {
                    var result = data.split('|');
                    if (result[0] == "True") {
                        if (result[1]) {
                            $.OKDialogAgency('<center>' + result[1] + '</center>', '提示', function () {
                                art.dialog.get("dialogProprietorEditEmployee").close();
                                window.location.reload();
                            });
                        }
                        else {
                            $.OKDialogAgency('<center>操作成功！</center>', '提示', function () {
                                art.dialog.get("dialogProprietorEditEmployee").close();
                                window.location.reload();
                            });
                        }
                    }
                    else if (result[0] == "False") {
                        $.OKDialogAgency('<center>' + result[1] + '</center>', '提示', function () {
                            $(".btneditEmployee").val("保存");
                        });
                    }
                    else {
                        $.OKDialogAgency('<center>' + result + '</center>');
                    }
                    $("#spanEditemployee .btneditEmployee").removeAttr("disabled");
                    employeeIndex.moreSubmit($("#spanEditemployee .btneditEmployee"), "btn-gray", "btn-red", false);
                });
            }
        });
    });

    //批量同步人员
    $(".btn-syncUserInfo").on("click", function () {
        if ($("#treeTable .checkStaff:checked").length > 0) {
            var admPermisstion = $(this).attr("data-permisstion");
            var employeeKeyId = employeeIndex.GetEmployeeKeys();
            var reqData = {
                "AdmPermission": admPermisstion,
                "userKeyIds": employeeKeyId
            };
            $.AjaxAgency("/system/sync-employeeBulk", reqData, function (data) {
                if (data == "OK") {
                    $.OKDialogAgency('<div class="tc">操作成功！</div>', '提示', function () {
                        $(".userSubmit").submit();
                    });
                }
                else {
                    $.OKDialogAgency('<div class="tc">' + data + '</div>');
                }
            });

        }
        else {
            $.OKDialogAgency('<div class="tc">请选择要同步的员工</div>');
        }
    });

    //同步人员信息，通过员工编号获取CCHR中的员工信息
    $("#treeTable .syncUser").bind("click", function () {

        var userKeyId = $(this).attr("bbb");
        $.OKCancelDialogAgency("确认同步该员工在Agency中的信息吗？", "同步员工", true, function () {
            var url = "/System/sync-employee";
            var reqData = {
                "userKeyId": userKeyId
            };
            $.AjaxAgency(url, reqData, function (data) {
                if (data == "OK") {
                    $.OKDialogAgency('<div class="tc">操作成功！</div>', '提示', function () {
                        window.location = "/system/employee";
                    });
                }
                else {
                    $.OKDialogAgency('<div class="tc">' + data + '</div>');
                }
            });
        }, null);
    });
    // end 同步人员信息

    //动态添加部门和角色
    employeeIndex.editDepartRole = function () {
        $("#spanEditemployee").find(".editDepartRole").bind("click", function () {

            //编辑员工的部门时将锁定的下拉框显示出来
            $(".departAndRolehtml .lockFlag").show();
            $("#spanEditemployee").find(".departAndRole").append($(".departAndRolehtml").html());
            var i = 0;
            $("#spanEditemployee").find(".departAndRole > div").each(function () {
                i++;
                var lastDepartName = $(this).find(".addEmployeeDeparthidd").unbind();
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").unbind();

                var lastDepartName = $(this).find(".addEmployeeDeparthidd").attr("id", "txtEditEmployeeDepart" + i);
                //获取隐藏文本框的的ID
                var lastDepartKey = $(this).find(".addEmployeeDepartKeyhidd").attr("id", "txtEditEmployeeDepartKey" + i);
                //每次添加都会给一个新的ID
                EmployeePrompt.getDepartAndEmployeeByInput(lastDepartName.attr("id"), lastDepartKey.attr("id"), null, null, false, false, 1, null, "");
            })
        });
    }
    //编辑员工相关方法结束 end
};
